package com.airlines.base.config.controller;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * @author xxxx
 * @date 2018年6月1日
 * @description 自定义时间绑定转换 接受格式：
 * 1、yyyy-MM-dd HH:mm:ss 
 * 2、yyyy-MM-dd 
 * 3、毫秒时间戳,秒时间戳
 */
public class MyDateTimePropertyEditorSupport extends PropertyEditorSupport {
	private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
	private static final String shortDateFormat = "yyyy-MM-dd";

	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		if (StringUtils.isBlank(text)) {
			setValue(null);
		}
		text = text.trim();
		try {
			if (text.contains("-")) {
				DateTimeFormatter  formatter;
				if (text.contains(":")) {
					formatter = DateTimeFormat.forPattern(dateFormat);
				} else {
					formatter = DateTimeFormat.forPattern(shortDateFormat);
				}
				DateTime dtDateTime = DateTime.parse(text,formatter);
				setValue(dtDateTime);
			} else if (text.matches("^\\d+$")) {
				if(text.length()<13){
					//传入的时间戳为秒，Unix timestam，需要转换成毫秒
					text = text+"000";
				}
				Long lDate = new Long(text);
				
				setValue(new DateTime(lDate));
			}
		} catch (Exception e) {
			throw new RuntimeException(String.format("parser %s to DateTime fail", text));
		}
	}

}
